package me.shurufa.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import me.shurufa.R;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.NetworkConstants;
import me.shurufa.utils.Global;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.Utils;
import okhttp3.Request;

/**
 * 修改头像页面
 *
 * @FileName: me.shurufa.activities.ModifyAvatarActivity.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-18 18:35
 */
public class ModifyAvatarActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.user_avatar)
    ImageView userAvatar;
    @Bind(R.id.modify_avatar_button)
    Button modifyAvatarButton;
    @Bind(R.id.modify_complete_button)
    Button modifyCompleteButton;

    private static final int PICK_PHOTO = 1;
    private String mPath;
    private KProgressHUD kProgressHUD;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_modify_avatar;
        super.onCreate(savedInstanceState);
        initUI();
    }

    private void initUI() {
        if (!TextUtils.isEmpty(Global.currentUser.avatar)){
            Glide.with(this).load(Global.currentUser.avatar).into(userAvatar);
        }else {
            //TODO 设置默认头像
            userAvatar.setImageResource(R.drawable.default_avatar);
        }
        modifyAvatarButton.setOnClickListener(this);
        modifyCompleteButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.modify_avatar_button:
                Intent intent = new Intent(ModifyAvatarActivity.this,PhotoPickerActivity.class);
                intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);
                intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_SINGLE);
                intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 1);
                startActivityForResult(intent, PICK_PHOTO);
                break;
            case R.id.modify_complete_button:
                Map<String, String> params = new HashMap<String, String>();
                params.put("token", Global.currentUser.token);
                if (TextUtils.isEmpty(mPath)){
                    finish();
                }else {
                    File file = new File(mPath);
                    kProgressHUD = KProgressHUD.create(this);
                    kProgressHUD.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                            .setLabel(getString(R.string.commit_pls_wait))
                            .setCancellable(false)
                            .setAnimationSpeed(2)
                            .setDimAmount(0.5f)
                            .show();
                    OkHttpUtils.post()//
                            .addFile("avatar", file.getName(), file)//
                            .url(NetworkConstants.USER_MODIFY_AVATAR)
                            .params(params)//
                            .build()//
                            .execute(new StringCallback() {
                                @Override
                                public void inProgress(float progress) {}
                                @Override
                                public void onError(Request request, Exception e) {
                                    Utils.showToast("提交失败");
                                    if (kProgressHUD != null) {
                                        kProgressHUD.dismiss();
                                        kProgressHUD = null;
                                    }
                                }
                                @Override
                                public void onResponse(String s) {
                                    doOkHttpResponse(s);
                                }
                            });
                }
                break;
        }
    }

    private void doOkHttpResponse(String s) {
        if (!TextUtils.isEmpty(s)) {
            LogUtils.kLog().d(s);
        }
        BaseResponse result = null;
        try{
            if (!TextUtils.isEmpty(s)){
                result = Global.getGson().fromJson(s,BaseResponse.class);
            }else {
                result = null;
            }
            if (result != null && result.success) {
                //TODO EventBus 通知外部刷新
                finish();
            } else {
                Utils.showToast("提交失败");
            }
        }catch (Exception e){}
        finally {
            if (kProgressHUD!=null){
                kProgressHUD.dismiss();
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == PICK_PHOTO){
            if(resultCode == RESULT_OK){
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                showAvatar(result);
            }
        }
    }

    private void showAvatar(ArrayList<String> result) {
        if (result!=null&&result.size()>0){
            mPath = result.get(0);
        }
        if (!TextUtils.isEmpty(mPath)){
            Glide.with(this).load(mPath).into(userAvatar);
        }
    }
}
